<template>
  <div id="vxePulldownSelection">
    <vxe-pulldown :ref="'xDown4' + compId" transfer span="24" style="width: 100%">
      <template #default>
        <vxe-input :ref="'txtInput' + compId" class-name="width-100-percentage" class="enterNextInputFlag"
          v-model="inputText" autocomplete="off" auto-complete="new-password" :disabled="caUse" :readonly="isReadonly"
          suffix-icon="vxe-icon-search" placeholder="请选择" @click="mouseClick" @keydown="enterConfirmEvent"
          @focus="focusEvent4" @blur="blurEvent4" @change="inputChange" @suffix-click="suffixClick4"
          @clear="clearConfirmEvent" clearable></vxe-input>
      </template>
      <template #dropdown>
        <div class="my-dropdown4 radius round shadow-warp lines-orange solid"
          :style="{ width: panelWidth, height: panelHeight }">
          <vxe-grid :ref="'gridTable4' + compId" :auto-resize="true" :scroll-y="{ enabled: true }" border show-overflow
            height="auto" width="auto" :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{
              isArrow: true,
              isEnter: true,
              editMethodExmItem4
            }" :edit-config="{ mode: 'row' }" :column-config="{ resizable: false }" :loading="loading"
            :pager-config="isPage ? tablePage4 : null" :data="tableList" :columns="tableColumn"
            @cell-click="cellClickEvent4" @page-change="pageChangeEvent4"></vxe-grid>
        </div>
      </template>
    </vxe-pulldown>
    <!-- <span>这是组件</span> -->
  </div>
</template>
<script lang="ts" setup>
//#region  依赖注入
import { ref, reactive, getCurrentInstance, nextTick, onMounted, watch, computed } from 'vue';
import { pageSizes, IsEmpty, newGuid } from '@/utils/common';

//#region  变量
let { proxy }: any = getCurrentInstance();
let a = reactive(pageSizes);
let b = ref(newGuid());
let compId: string = newGuid();
let keyvalue = ref('');
let caUse = ref(false);
let isReadonly = ref(false);
let loading = ref(false);
let tablePage4 = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 200
});
let tableList = reactive([]);
let tableListBase = reactive([]);/**列表集合影子，供关键字查询使用 */
//let tableColumn = reactive([]);
let totalCount = 0;
let isEnterConfirm = ref(false);/**是否回车确定 */
let selectedItem = {
  id: null,
  name: ''
};
let iscanShowPanel = ref(false);/**授权弹窗关闭 时 不在弹下拉选择面板 */
// 父组件传值
let props = defineProps({
  url: String, //数据请求地址
  requestType: { type: String, default: 'get' }, //请求方式
  tableColumn: Array as () => String[], //列集合
  displayTexts: Array as () => String[], //显示字段集合
  displayTextObj: String, //显示字段集合
  dataObj: {}, //接口参数。{key1:value1,key2:value2...}
  isDisabled: Boolean, //是否可用
  isReadonly: Boolean, //是否只读
  isChild: Boolean, //是否子行
  childIndex: Number, //子航索引
  aimKeys: Array as () => String[], //目标字段
  resItem: String, //返回数据中，包含所需数据的名称
  isChangeName: Boolean, //输入框内容是否可手动更改
  compName: String, //组件名称
  dataName: String, //请求数据结构名称
  isRow: Boolean,
  rowIndex: String,
  panelWidth: { type: String, default: '450px' },
  panelHeight: { type: String, default: '300px' },
  isPage: { type: Boolean, default: false } //是否需要分页
}) as any;

watch(
  () => props.displayTextObj,
  (n, o) => {
    keyvalue.value = n;
    if (!tableList || tableList.length <= 0) {
      findList();
    }
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => props.isDisabled,
  (newval, oldvbal) => {
    caUse.value = newval;
  },
  {
    deep: true,
    immediate: true
  }
);

//#endregion

//#region  计算属性
let isKeySearch = ref(false);/**是否关键字查询 */
const inputText = computed(() => {
  if (isEnterConfirm.value) {
    //TODO
  }
  let v = '';
  try {
    const aim = tableList.filter((p) => p[props.aimKeys[0].rowKey] === keyvalue.value || p[props.aimKeys[0].rowKey] === props.displayTextObj);
    if (aim && aim.length > 0) {
      v = aim[0][props.tableColumn[1].field];
    } else {
      v = props.displayTextObj;
    }
    return v;
  } catch (error) {
    v = '';
  }
  return keyvalue.value;
});
//#endregion

//#region  属性

//#endregion

//#region  监听器

//#endregion

//#endregion

defineExpose({
  resetDisplayText, /**重置显示文本 */
  hidePulldownPanel,/**隐藏下拉选择面板 */
  noShowPanel,/**授权关闭不需要再弹窗 */
});

//#region  生命周期函数
onMounted(() => {
  //todo
});
//#endregion

//#region  函数
function findList() {
  loading.value = true;
  tableList.length = 0;
  tableListBase.length = 0;
  if (IsEmpty(proxy.url)) {
    loading.value = false;
    return;
  }

  let url = proxy.url;
  let data: any = {
    filter: IsEmpty(selectedItem.name) ? null : selectedItem.name.toString().trim().toUpperCase(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize
    //inputCode:IsEmpty(this.selectedItem.name) ? null : this.selectedItem.name.toString().trim().toUpperCase(),
  };
  // 循环父组件传来的特殊查询字段，添加到data上
  if (!IsEmpty(proxy.dataObj)) {
    for (const key in proxy.dataObj) {
      if (proxy.dataObj[key]) {
        data[key] = proxy.dataObj[key];
      }
    }
  }
  if (proxy.requestType === 'post') {
    tableList.length = 0;
    tableListBase.length = 0;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        tableList.length = 0;
        tableListBase.length = 0;
        tableList.push(...res.data);
        Object.assign(tableListBase, res.data);
        loading.value = false;
        proxy.$nextTick(() => {
          const $xTable = proxy.$refs['gridTable4' + compId] as any;
          if ($xTable) {
            $xTable.focus();
            if (tableList.length > 0) {
              $xTable.setCurrentRow(tableList[0]);
            }
          }
        });
      })
      .catch((err: any) => {
        loading.value = false;
      });
  } else {
    tableList.length = 0;
    tableListBase.length = 0;
    proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        tableList.length = 0;
        tableListBase.length = 0;
        tableList.push(...res.data);
        Object.assign(tableListBase, res.data);
        loading.value = false;
        proxy.$nextTick(() => {
          const $xTable = proxy.$refs['gridTable4' + compId] as any;
          if ($xTable) {
            $xTable.focus();
            if (tableList.length > 0) {
              $xTable.setCurrentRow(tableList[0]);
            }
          }
        });
      })
      .catch((err: any) => {
        loading.value = false;
      });
  }
}

/**重置显示信息 */
function resetDisplayText(text: String, callback) {
  if (tableList.length <= 0) {
    findList();
  }
  keyvalue.value = text;
  if (callback) {
    callback();
  }
}

// 获取列表
function findListWithUrl(pUrl: string) {
  if (IsEmpty(pUrl)) {
    tableList = [];
    return;
  }
  //#region  判断请求接口地址为空
  if (IsEmpty(proxy.url)) {
    loading.value = false;
    tableList = [];
    return;
  }
  //#endregion
  let url = pUrl;
  let data: any = {
    filter: IsEmpty(selectedItem.name) ? null : selectedItem.name.toString().trim(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize
  };

  if (!IsEmpty(proxy.dataObj)) {
    for (const key in proxy.dataObj) {
      if (proxy.dataObj[key]) {
        data[key] = proxy.dataObj[key];
      }
    }
  }

  tableListBase.length = 0;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      tableList.length = 0;
      tableListBase.length = 0;
      tableList = res.data; //.push(...res.data);
      Object.assign(tableListBase, res.data);
      tablePage4.total = res.totalCount;
      // this.$forceUpdate();
      loading.value = false;
    })
    .catch((err: any) => {
      //loading = false;
      //.$alert(err.data.error.message, '提示');
    });
}

//回车选中
async function enterConfirmEvent({ value, $event }) {
  if ($event && ($event.keyCode === 13 || $event.keyCode === 9)) {
    isEnterConfirm.value = true;
    const $xTable = proxy.$refs['xDown4' + compId] as any;
    if ($xTable.isPanelVisible()) {
      const gridTable = proxy.$refs['gridTable4' + compId] as any;
      const rowSelect = gridTable.getCurrentRecord();
      cellClickEvent4({ row: rowSelect });
      await $xTable.hidePanel();
    }
  } else {
    isKeySearch.value = true;
  }
}
/**鼠标点击事件 */
function mouseClick() {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  if ($xTable.isPanelVisible()) {
    return;
  }

  findList();
  //todo

  if ($xTable) {
    $xTable.showPanel();
  }
}
// 获取焦点
function focusEvent4() {
  if (iscanShowPanel.value) {
    iscanShowPanel.value = false;
    return;
  }
  const txtInputRef = proxy.$refs['txtInput' + compId] as any;
  if (txtInputRef) {
    txtInputRef.select();
  }

  const $xTable = proxy.$refs['xDown4' + compId] as any;
  if ($xTable.isPanelVisible()) {
    return;
  }

  findList();
  //todo

  if ($xTable) {
    $xTable.showPanel();
  }
}
// 失去焦点
function blurEvent4(e) {
  // 输入框内容未改变
  if (e.value === proxy.displayTextObj) {
    return;
  }
  if (proxy.isChangeName) {
    this.$emit('changeName', e.value);
  }
}

// 值改变
function inputChange({ value }) {
  //debugger;
  selectedItem.name = value;
  /**非回车键 视为关键字查询 */
  if (isKeySearch.value && !IsEmpty(value)) {
    /**关键字搜索时调用 */
    try {
      tableList.length = 0;
      const aim = tableListBase.filter((p: any) => {
        // const a = 'realname';
        // const b = 'username';
        // const c = 'code';
        // const d = 'code';
        // if (p && (p[a] || p[b] || p[c] || p[d]) && value) {
        //   return (p[a].includes(value) || p[b].includes(value) || p[c] || p[d])
        // }
        const a = 'inputCode';
        const b = 'name';
        const c = 'sampleTypeName'; //样本类型
        const d = 'realname'; //检验医师 审核医师
        let match = true;
        let forOrvalidate = false;/**只要有一个条件满足，则满足 */

        props.aimKeys.forEach((m: any) => {
          if (m.rowKey == 'id') {
            if ((m.rowKey && p[m.rowKey] && p[m.rowKey] == value) || (m.rowKey2 && p[m.rowKey2] && p[m.rowKey2].includes(value)) || (m.rowKey3 && p[m.rowKey3] && p[m.rowKey3].includes(value))) {
              forOrvalidate = true;
            }
          } else {
            if ((m.rowKey && p[m.rowKey] && p[m.rowKey].includes(value)) || (m.rowKey2 && p[m.rowKey2] && p[m.rowKey2].includes(value)) || (m.rowKey3 && p[m.rowKey3] && p[m.rowKey3].includes(value))) {
              forOrvalidate = true;
            }
          }
        });
        if (!forOrvalidate) {
          match = false;
        }

        //助记码a 名字b
        if (p[a] && p[a].includes(value) || p[b] && p[b].includes(value) || p[c] && p[c].includes(value) || p[d] && p[d].includes(value)) {
          match = true;
        }
        return match;
      });
      if (aim && aim.length > 0) {
        Object.assign(tableList, aim);
      }
      selectRow();
      isKeySearch.value = false;
    } catch (error) {
      //todo
    }
  } else {
    if (IsEmpty(value)) {
      clearConfirmEvent();
      
    } else {
      if (tableListBase.length > 0) {
        tableList.length = 0;
        Object.assign(tableList, tableListBase);
      } else {
        findList();
      }
    }

  }
  isKeySearch.value = false;
}

function keyupEvent4() {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.showPanel();
}

function suffixClick4() {
  //todo
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.togglePanel();
}
// 清空
function clearConfirmEvent() {
  let a = { id: null } as any;
  try {
    props.aimKeys.forEach(e => {
      a[e.rowKey] = null;
    });
  } catch (error) {
    //todo
  }
  proxy.$emit('confirmClick', {
    isChild: proxy.isChild,
    childIndex: proxy.childIndex,
    row: { ...a, entity: a },
    aimKeys: proxy.aimKeys,
    compName: proxy.compName
  });
}
function editMethodExmItem4() {
  //todo
}
//行选中
function cellClickEvent4({ row }) {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.hidePanel();
  if (IsEmpty(row)) {
    return;
  }
  keyvalue.value = row && props.aimKeys[0] && row[props.aimKeys[0].rowKey] ? row[props.aimKeys[0].rowKey] : '';
  proxy.displayTexts.forEach((element) => {
    // 判断父组件传来的数据是否是对象的深层键名
    const keyArr = element.split('.');
    if (keyArr.length > 1) {
      let res = null;
      let data = row;
      keyArr.forEach((key, index) => {
        if (index > 0) {
          data = res;
        }
        res = data[key];

        if (index === keyArr.length - 1) {
          keyvalue.value += res + ' ';
        }
      });
    } else {
      //keyvalue.value += row[element] + ' ';
    }
  });

  proxy.$emit('confirmClick', {
    isRow: proxy.isRow,
    rowIndex: proxy.rowIndex,
    row: { ...row, entity: row },
    aimKeys: proxy.aimKeys,
    compName: proxy.compName,
    isChild: proxy.isChild,
    childIndex: proxy.childIndex
  });
  isEnterConfirm.value = false;
}
function pageChangeEvent4({ type, currentPage, pageSize }) {
  tablePage4.currentPage = currentPage;
  tablePage4.pageSize = pageSize;
  findList();
}
function selectRow() {
  const $xTable = proxy.$refs['gridTable4' + compId] as any;
  if ($xTable) {
    $xTable.focus();
    if (tableList.length > 0) {
      $xTable.setCurrentRow(tableList[0]);
    }
  }
}
function hidePulldownPanel() {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.hidePanel();
}
function noShowPanel() {
  iscanShowPanel.value = true;
}
//#endregion
</script>
<style lang="scss" scoped>
#vxePulldownSelection {
  :deep(.my-dropdown4) {
    padding: 4px;
    min-width: 400px;
    height: 450px;
    background-color: #fff;
    box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
    cursor: pointer;
  }

  :deep(.vxe-pager.size--mini) {
    height: 33px !important;
  }
}
</style>
